package app.fugema.shop.main.wallet.view;

import android.content.DialogInterface;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import app.fugema.shop.main.order.view.PayResultActivity;
import app.fugema.shop.main.wallet.model.PayBen;
import app.fugema.shop.main.wallet.model.PayInfoResult;
import app.fugema.shop.main.wallet.model.WxpayInfo;

import com.base.common.app.BaseConstant;
import com.base.common.app.LoginUtils;
import com.base.common.model.bean.PayResponse;
import com.base.common.model.bean.WeChatPayResponse;
import com.base.common.model.http.jackSon.JacksonUtils;
import com.base.common.netBeanPackage.LiveDataWrapper;
import com.base.common.utils.DensityUtil;
import com.base.common.utils.LogUtil;
import com.base.common.utils.OnClickCheckedUtil;
import com.base.common.utils.RxTimer;
import com.base.common.utils.UIUtils;
import com.base.common.view.adapter.MyLinearLayoutManager;
import com.base.common.view.adapter.ada.BaseRVAdapter;
import com.base.common.view.adapter.ada.SingleRecyclerAdapter;
import com.base.common.view.base.BaseDialogFragment;
import com.base.common.viewmodel.BaseViewObserver;
import app.fugema.shop.helper.AlipayHelper;

import com.jeremyliao.liveeventbus.LiveEventBus;
import app.fugema.shop.R;
import app.fugema.shop.main.order.model.CheckOrderStatusResult;
import app.fugema.shop.main.order.model.OrderStatus;
import app.fugema.shop.main.order.model.PaymentResult;
import app.fugema.shop.constants.AppConstants;
import app.fugema.shop.databinding.WalletPayDialogFragmentBinding;
import app.fugema.shop.databinding.WalletPayItemBinding;
import app.fugema.shop.helper.WeChatHelper;
import app.fugema.shop.main.order.vm.OrderConfirmVN;
import app.fugema.shop.main.wallet.model.BuyBean;


import java.util.List;

public class WalletPayDialogFragment extends BaseDialogFragment<WalletPayDialogFragmentBinding, OrderConfirmVN> {

    public static WalletPayDialogFragment newInstance(BuyBean bean)
    {
        Bundle args = new Bundle();
        WalletPayDialogFragment fragment = new WalletPayDialogFragment();
        fragment.setArguments(args);
        fragment.setBuyBean(bean);
        return fragment;
    }

    @Override
    protected WalletPayDialogFragmentBinding initDataBinding(LayoutInflater inflater, ViewGroup container)
    {
        return DataBindingUtil.inflate(inflater, R.layout.wallet_pay_dialog_fragment, container, false);
    }

    private BuyBean buyBean;//需要支付的
    private SingleRecyclerAdapter<PayBen, WalletPayItemBinding> adapter;

    private String userKey;

    private RxTimer rxTimer;

    public void setBuyBean(BuyBean buyBean)
    {
        this.buyBean = buyBean;
    }

    @Override
    public void initView()
    {
        super.initView();
        binding.ivBack.setOnClickListener(new OnClickCheckedUtil() {
            @Override
            public void onClicked(View view) {
                dismissAllowingStateLoss();
            }
        });

        userKey = LoginUtils.getToken();

        binding.rvRecycler.setLayoutManager(new MyLinearLayoutManager(getContext()));
        adapter = new SingleRecyclerAdapter<PayBen, WalletPayItemBinding>() {
            @Override
            public int getLayoutId()
            {
                return R.layout.wallet_pay_item;
            }

            @Override
            public void onBindViewHolder(WalletPayItemBinding binding, int position, PayBen bean)
            {
                super.onBindViewHolder(binding, position, bean);
            }

            @Override
            public void onItemClick(View view, BaseRVAdapter adapter, int onclickType, int position, PayBen bean)
            {
                if (bean.getPayType() == "0")
                {
                    LogUtil.e( "未获取到余额" );
                }
                setSelectPosition(position);
            }
        };
        adapter.setRadio(true);
        binding.rvRecycler.setAdapter(adapter);

        binding.tvOk.setOnClickListener(new OnClickCheckedUtil() {
            @Override
            public void onClicked(View view) {
                if (adapter != null && buyBean != null)
                {
                    PayBen payBen = adapter.getSelectBean();
                    if (payBen != null)
                    {
                        //payBen.getPayType()
                        if(  payBen.getPayType().equals("WeiXinPay_App")  )
                        {
                            buyBean.setPayType( 1 );
                        }
                        else if( payBen.getPayType().equals("Alipay_App") )
                        {
                            buyBean.setPayType( 2 );
                        }

                        startParOrder( buyBean.getOrderNumbers()  , payBen.getPayType() );
                    }
                    else
                    {
                        UIUtils.showToastSafes("请选择支付方式");
                    }
                }
            }
        });

        //接收微信支付
        LiveEventBus.get(AppConstants.PAY_NOTIFY, PayResponse.class).observe(this, new Observer<PayResponse>() {
            @Override
            public void onChanged(PayResponse o)
            {
                if (o.getPayStatus() == PayResponse.PayStatus.STATUS_SUCCESS)
                {
                    //微信支付成功
                    UIUtils.showToastSafes("微信支付成功");
                }
                else if( o.getPayStatus() == PayResponse.PayStatus.STATUS_CANCEL )
                {
                    //微信支付取消
                    UIUtils.showToastSafes("微信支付已取消");
                }
                else if(  o.getPayStatus() == PayResponse.PayStatus.STATUS_FAIL )
                { //微信支付失败
                    UIUtils.showToastSafes("微信支付失败");
                }
                else
                {
                    UIUtils.showToastSafes("未知错误");
                }
            }
        });

        if (rxTimer == null)
        {
            rxTimer = new RxTimer();
        }
    }

    @Override
    public void initData()
    {
        super.initData();
        binding.setItem(buyBean);

//        PayBen payBen = new PayBen();
//        payBen.setPayType(0);
//        payBen.setName("钱包支付");
//        list.add(payBen);
        // 查询支付方式
        queryEnablePayList(userKey);
    }

    // 根据支付 方式 获取 支付信息
    public void startParOrder(String orderIds,String typeId)
    {
        viewModel.getPayInfoByOrderId( orderIds,typeId, userKey).observe(this, new BaseViewObserver<LiveDataWrapper<PayInfoResult>>(getActivity())
        {
            @Override
            protected void onSuccess(LiveDataWrapper<PayInfoResult> data)
            {
                /*
                {"success":true,
                        "data":[{"id":"Himall.Plugin.Payment.Alipay_App",
                        "name":"支付宝支付",
                        "logo":"alipay.gif",
                        "url":"app_id=2019062065633602&biz_content=%7b%22out_trade_no%22%3a%22210531111638275197%22%2c%22product_code%22%3a%22QUICK_MSECURITY_PAY%22%2c%22subject%22%3a%22%e6%9c%a8%e6%9e%97%e6%a3%ae+%e7%94%b7%e5%a3%ab%e6%96%b0%e6%ac%be%e7%a7%8b%e5%ad%a3%e5%8d%ab%e8%a1%a3%e7%94%b7%e9%9f%a9%e7%89%88%e6%98%a5%e7%a7%8b%e5%ad%a6%e7%94%9f%e5%ae%bd%e6%9d%be%e6%bd%ae%e6%b5%81%e7%94%b7%e8%a3%85%e5%a4%96%e5%a5%97%e5%a4%a7%e7%a0%81%22%2c%22timeout_express%22%3a%2260m%22%2c%22total_amount%22%3a%22129.00%22%7d&charset=UTF-8&format=json&method=alipay.trade.app.pay&notify_url=https%3a%2f%2fwww.fugema.cn%2fm-Android%2fPayment%2fNotify%2fHimall-Plugin-Payment-Alipay_App%2f&sign_type=RSA2&timestamp=2021-05-31+16%3a11%3a38&version=1.0&sign=Oeme1oWZK1kU6zmzQtCpkCitWH%2fiPzMATWEDggiPvOLWcR64zClxG073bDjR1vZ2PwhKksNLFuknpMZYEWGtDQZIZY7X80ML0bJntdC%2fBM0Iu7583soGTURMFvoIaH1F%2b%2fv3gAIspIhUHVOVqxk%2fh54rYbUczlwVzNN9OBmjx420ymagswQuXkL4cAqO6paIa%2b%2f5mdnVgxcRdw0g6OXCYoWI2EEtw4xLjYQGaYQm3RuvpNL8MStYZeprHEEg4WJN8EvYe%2bMIGhF7fEGDcAH2qXEe1wFnX0CHmVF%2fUAX5bDelaMgRxo8ajT9021AGN4Ovo8KmZskOyp3DwNGmYLsfhQ%3d%3d"}]}
                */
                /*
                {"success":true,
                  "data":[{"id":"Himall.Plugin.Payment.WeiXinPay_App","name":"微信支付","logo":"wx_logo.png","url":"{\"prepayid\":\"wx09105107502939236da35e0f8c89170000\",\"timestamp\":1623207067,\"package\":\"Sign=WXPay\",\"sign\":\"133B7A895F5C73279B96FDC8319D2B6F\",\"partnerid\":\"1540498461\",\"noncestr\":\"34ED066DF378EFACC9B924EC161E7639\",\"appid\":\"wx312605eb4f303ee4\"}"}]}
                */
                // 拿到支付信息
                if(data.data.isSuccess())
                {
                    if( UIUtils.isNotEmpty( data.data.getData() ) )
                    {
                        PayInfoResult.PayData payData = data.data.getData().get(0);
                        String payIdStr = payData.getId();
                        LogUtil.e("payId = " + payIdStr  );
                        String type = payIdStr.substring(payIdStr.lastIndexOf(".") + 1 , payIdStr.length() );
                        LogUtil.e("type = " + type  );
                        switch (type)
                        {
                            case "walletPay"://钱包
//                        walletPay(stateBean);
//                        break;
                            case "Alipay_App":
                                //支付宝
                                aliPay(payData.getUrl());
                                break;
                            case "WeiXinPay_App":
                                //微信
                                //"{\"prepayid\":\"wx09105107502939236da35e0f8c89170000\",\"timestamp\":1623207067,\"package\":\"Sign=WXPay\",\"sign\":\"133B7A895F5C73279B96FDC8319D2B6F\",\"partnerid\":\"1540498461\",\"noncestr\":\"34ED066DF378EFACC9B924EC161E7639\",\"appid\":\"wx312605eb4f303ee4\"}"
                                wxpayReq(payData.getUrl());
                                // 微信支付 结果 在 WXPayEntryActivity 中返回

                                break;
                            default:
                                UIUtils.showToastSafes("支付方式未知");
                                break;
                        }
                    }
                    else
                    {
                        UIUtils.showToastSafes("支付信息为空");
                    }
                }

                // 开始轮训  一直查询 订单支付状态    每3秒 查一次
                rxTimer.interval(3000, new RxTimer.RxAction() {
                    @Override
                    public void action(long number)
                    {
                        startChckeOrderPayStatus(buyBean.getOrderNumbers());
                    }
                });

            }
        });
    }
    //支付宝
    public void aliPay(String aliPayStr)
    {
//"app_id=2019062065633602&biz_content=%7b%22out_trade_no%22%3a%22210531111638275197%22%2c%22product_code%22%3a%22QUICK_MSECURITY_PAY%22%2c%22subject%22%3a%22%e6%9c%a8%e6%9e%97%e6%a3%ae+%e7%94%b7%e5%a3%ab%e6%96%b0%e6%ac%be%e7%a7%8b%e5%ad%a3%e5%8d%ab%e8%a1%a3%e7%94%b7%e9%9f%a9%e7%89%88%e6%98%a5%e7%a7%8b%e5%ad%a6%e7%94%9f%e5%ae%bd%e6%9d%be%e6%bd%ae%e6%b5%81%e7%94%b7%e8%a3%85%e5%a4%96%e5%a5%97%e5%a4%a7%e7%a0%81%22%2c%22timeout_express%22%3a%2260m%22%2c%22total_amount%22%3a%22129.00%22%7d&charset=UTF-8&format=json&method=alipay.trade.app.pay&notify_url=https%3a%2f%2fwww.fugema.cn%2fm-Android%2fPayment%2fNotify%2fHimall-Plugin-Payment-Alipay_App%2f&sign_type=RSA2&timestamp=2021-05-31+16%3a11%3a38&version=1.0&sign=Oeme1oWZK1kU6zmzQtCpkCitWH%2fiPzMATWEDggiPvOLWcR64zClxG073bDjR1vZ2PwhKksNLFuknpMZYEWGtDQZIZY7X80ML0bJntdC%2fBM0Iu7583soGTURMFvoIaH1F%2b%2fv3gAIspIhUHVOVqxk%2fh54rYbUczlwVzNN9OBmjx420ymagswQuXkL4cAqO6paIa%2b%2f5mdnVgxcRdw0g6OXCYoWI2EEtw4xLjYQGaYQm3RuvpNL8MStYZeprHEEg4WJN8EvYe%2bMIGhF7fEGDcAH2qXEe1wFnX0CHmVF%2fUAX5bDelaMgRxo8ajT9021AGN4Ovo8KmZskOyp3DwNGmYLsfhQ%3d%3d"
        AlipayHelper.pay(getActivity(), aliPayStr, new AlipayHelper.AlipayCallBack() {
            @Override
            public void onSucc()
            {
                UIUtils.showToastSafes("支付宝支付成功");
                //dismissAllowingStateLoss();
            }

            @Override
            public void onFail()
            {
                UIUtils.showToastSafes("支付宝支付失败");
                //dismissAllowingStateLoss();
            }
        });
    }

    private void queryEnablePayList(String mUserKey)
    {
        /*
        UIUtils.runInMainThread(new Runnable() {
            @Override
            public void run(){} });
        */
        viewModel.enablePaymentList(mUserKey).observe(WalletPayDialogFragment.this, new BaseViewObserver<LiveDataWrapper<PaymentResult>>(getActivity())
        {
            @Override
            protected void onSuccess(LiveDataWrapper<PaymentResult> data)
            {
                if (data.data.isSuccess())
                {
                    List<PayBen> payBenList = PayBen.getPayListByPaymentType( data.data.getData() );
                    //默认选择 第一个
                    payBenList.get(0).setSelected(true);
                    adapter.setDataList(payBenList);
                    //dismissAllowingStateLoss();
                }
                else
                {
                    UIUtils.showToastSafes("查询支付方式失败");
                }
            }

            @Override
            protected void onComplete()
            {
                super.onComplete();
            }
        });
        //关闭 dialog
        //dismissAllowingStateLoss();
    }

    //调起微信
    private void wxpayReq(String wxPayStr)
    {
        String jsonStr = wxPayStr;
        if( wxPayStr.contains("package") )
        {
            jsonStr =  wxPayStr.replace("package","packageX");
        }

        WxpayInfo data = JacksonUtils.getJsonBean(jsonStr ,WxpayInfo.class);

        WeChatPayResponse.PayInfoBean payInfoBean = new WeChatPayResponse.PayInfoBean();
        payInfoBean.setAppid(data.getAppid());
        payInfoBean.setNoncestr(data.getNoncestr());
        payInfoBean.setPackageX("Sign=WXPay");
        payInfoBean.setPartnerid(data.getPartnerid());
        payInfoBean.setPrepayid(data.getPrepayid());
        //String timeMillis = String.valueOf(System.currentTimeMillis() / 1000);
        //timeMillis
        payInfoBean.setTimestamp(data.getTimestamp());
        payInfoBean.setSign(data.getSign());
        WeChatHelper.pay(payInfoBean, false);
    }

    @Override
    public void onDestroy()
    {
        super.onDestroy();
    }

    @Override
    public int getGravity()
    {
        return Gravity.BOTTOM;
    }

    @Override
    protected int getHeight()
    {
        return DensityUtil.getDimens(R.dimen.dp_431);
    }

    /**
     *  轮训 查询
     * @param orderIds
     */
    private void startChckeOrderPayStatus(String orderIds)
    {
        viewModel.checkOrderPayStatus(orderIds, userKey)
                 .observe(this, new BaseViewObserver<LiveDataWrapper<CheckOrderStatusResult>>()
                 {
                     @Override
                     protected void onSuccess(LiveDataWrapper<CheckOrderStatusResult> data)
                     {
                           /*
                         {"success":true, "list":[{"groupsuccess":false,"orderId":2021070821966490,
                         "status":1,"activeId":0,"groupId":0}]}*/
                           //"status":1 待付款
                            if( data.data.isSuccess() )
                            {
                                for (OrderStatus orderStatus : data.data.getList())
                                {
                                     if( orderStatus.getStatus() == 2 )
                                     {
                                         if( rxTimer != null )
                                         {
                                             rxTimer.cancel();
                                         }
                                         UIUtils.showToastSafes("订单已支付");

                                         //通知相关页面关闭
                                         LiveEventBus.get(BaseConstant.EventKey.PAY_SUCCESS, String.class).post(buyBean.getOrderNumbers());
                                         // 支付完成后 在关闭 当前页面
                                         // 支付 完成信息 页面
                                         //ShoppingPayResultActivity.start(getActivity(), true, 0, buyBean.getOrderNumbers());
                                         PayResultActivity.start(getActivity());

                                         dismissAllowingStateLoss();
                                     }
                                }
                            }
                     }
                 });
    }

    @Override
    public void onDismiss(DialogInterface dialog)
    {
        super.onDismiss(dialog);
        if (rxTimer != null)
        {
            rxTimer.cancel();
        }
    }
}
